package lxy;

public class ThreadWork {
    public static void main(String[] args) {

        //将共享数据封装在另外一个对象中，然后将这个对象逐一传递给各个Runnable对象。
        //每个线程对共享数据的操作方法也分配到那个对象身上去完成，
        //这样容易实现针对该数据进行的各个操作的互斥和通信。
        final ShareDate shareDate = new ShareDate();
        Thread t1 = new Thread(new T1(shareDate),"第一个加法线程：");
        Thread t2 = new Thread(new T1(shareDate),"第二个加法线程：");
        Thread t3 = new Thread(new T2(shareDate),"第三个减法线程：");
        Thread t4 = new Thread(new T2(shareDate),"第四个减法线程：");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }

    static class T1 implements Runnable {

        private ShareDate shareDate;

        public T1(ShareDate shareDate) {
            this.shareDate = shareDate;
        }

        @Override
        public void run() {
            shareDate.addDate();
        }
    }

    static class T2 implements Runnable {

        private ShareDate shareDate;

        public T2(ShareDate shareDate) {
            this.shareDate = shareDate;
        }

        @Override
        public void run() {
            shareDate.cutDate();
        }
    }

    static class ShareDate{
        int count = 100;

        public synchronized void addDate(){
            count++;
            System.out.println(Thread.currentThread().getName() + count);
        }

        public synchronized void cutDate(){
            count--;
            System.out.println(Thread.currentThread().getName() + count);
        }
    }
}


